package com.ruoyi.common.utils.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * pdf转图片工具类
 *
 * @author fc
 * @version 1.0
 * @since 2021-05-17
 */
public class PdfToImageUtil {

    public static String watermark(File file, String pdfFontPath, String markStr) throws Exception {
        //创建新pdf文件
        String filePath = file.getParent() + System.getProperty("file.separator") + "TMP_" + file.getName();
        File tmpPDF = new File(filePath);
        //打开pdf文件
        PDDocument doc = PDDocument.load(file);
        doc.setAllSecurityToBeRemoved(true);
        //遍历pdf所有页
        for (PDPage page : doc.getPages()) {
            PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
            //水印名称
            //引入字体文件 解决中文汉字乱码问题
            PDFont font = PDType0Font.load(doc, new FileInputStream(pdfFontPath), true);
//            PDFont font = PDType0Font.load(doc, new FileInputStream(new File("").getCanonicalPath()+"\\cndmega-extend\\src\\main\\resources\\font\\msyh.ttf"), true);
            float fontSize = 30;
            PDResources resources = page.getResources();
            PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
            // 水印透明度
            r0.setNonStrokingAlphaConstant(0.2f);
            r0.setAlphaSourceFlag(true);
            cs.setGraphicsStateParameters(r0);
            //水印颜色
            cs.setNonStrokingColor(204, 204, 204);
            cs.beginText();
            cs.setFont(font, fontSize);
            //根据水印文字大小长度计算横向坐标需要渲染几次水印
            float h = markStr.length() * fontSize;
            for (int i = 0; i <= 10; i++) {
                // 获取旋转实例
                cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 100, 0));
                cs.showText(markStr);
                for (int j = 0; j < 20; j++) {
                    cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 100, j * h));
                    cs.showText(markStr);
                }
            }
            cs.endText();
            cs.restoreGraphicsState();
            cs.close();
        }
        //保存位置
        doc.save(tmpPDF);

//        FileItem fileItem = getMultipartFile(tmpPDF,"templFileItem");
        return filePath;
    }

    /**
     * 将file转换成fileItem
     * @param file
     * @param fieldName
     * @return
     */
    public static FileItem getMultipartFile(File file, String fieldName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

}
